package com.birtboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            /*
                测试读取请求行
                请求行是请求的一行内容,以回车符+换行符结尾的一行字符串
             */
            String line = readLine();
            System.out.println("请求行:" + line);
            //将请求行中的请求方式,抽象路径,协议版本分别解析出来
            String method;
            String uri;
            String protocol;
//          GET /index.html HTTP/1.1
            String[] data = line.split("\\s");
            method = data[0];
            uri = data[1];
            protocol = data[2];
            //http://localhost:8088/index.html
            System.out.println("method:" + method);
            System.out.println("uri:" + uri);
            System.out.println("protocol:" + protocol);
            //V3新加内容:
            //1.2解析消息头
            //用一个Map保存所有消息头,key保存消息头名字  value保存该消息头对应的值
            Map<String, String> headers = new HashMap<>();
            while (true) {
                line = readLine();
                if (line.isEmpty()) {
                    break;
                }
                System.out.println("消息头:" + line);
                data = line.split(":\\s");
                headers.put(data[0], data[1]);
            }
            System.out.println("headers:" + headers);

            //2处理请求

            //3发送响应

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //遵循HTTP协议要求,一问一答后与客户端断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private String readLine() throws IOException {
        /*
            socket对象没有发生改变,那么无论调用这个对象多少次获取流的操作时,获取的始终是
            同一条流(输入,输出都一样)
         */
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();//保存拼接后的一行字符串
        char cur = 'a', pre = 'a';//cur表示本次读取的字符  pre表示上次读取的字符
        while ((d = in.read()) != -1) {
            cur = (char) d;//将本次读取的字符赋值给cur
            if (pre == 13 && cur == 10) {//判断上次是否读取的回车符,本次是否为换行符
                break;//若连续读取了回车+换行就停止读取(一行结束了)
            }
            builder.append(cur);
            pre = cur;//在读取下一个字符前,将本次读取的字符记作"上次读取的字符"
        }
        return builder.toString().trim();
    }
}
